package com.tengfei.main.course.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tengfei.common.core.domain.PageQuery;
import com.tengfei.common.core.page.TableDataInfo;
import com.tengfei.common.exception.ServiceException;
import com.tengfei.main.course.domain.Chapter;
import com.tengfei.main.course.domain.Course;
import com.tengfei.main.course.domain.bo.CourseBo;
import com.tengfei.main.course.domain.vo.CourseVo;
import com.tengfei.main.course.mapper.ChapterMapper;
import com.tengfei.main.course.mapper.CourseMapper;
import com.tengfei.main.course.service.ICourseService;
import com.tengfei.main.plan.domain.PlanCourses;
import com.tengfei.main.plan.mapper.PlanCoursesMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * 课程Service业务层处理
 *
 * @author ruoyi
 * @date 2022-07-27
 */
@Service
public class CourseServiceImpl implements ICourseService {

    @Resource
    private CourseMapper baseMapper;
    @Resource
    private ChapterMapper chapterMapper;

    // 防止循环依赖
    @Resource
    private PlanCoursesMapper planCourseMapper;


    /**
     * 查询课程
     */
    @Override
    public CourseVo queryById(Long courseId) {
        CourseVo courseVo = baseMapper.selectVoById(courseId);
        return courseVo;
    }

    /**
     * 查询课程列表
     */
    @Override
    public TableDataInfo<CourseVo> queryPageList(CourseBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Course> lqw = buildQueryWrapper(bo);
        Page<CourseVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    private LambdaQueryWrapper<Course> buildQueryWrapper(CourseBo bo) {
        return new LambdaQueryWrapper<Course>()
                .eq(ObjectUtil.isNotNull(bo.getCourseIsBegin()), Course::getCourseIsBegin, bo.getCourseIsBegin())
                .eq(ObjectUtil.isNotNull(bo.getCourseIsPublic()), Course::getCourseIsPublic, bo.getCourseIsPublic())
                .like(ObjectUtil.isNotNull(bo.getSearchValue()), Course::getCourseTitle, bo.getSearchValue())
                .or()
                .like(ObjectUtil.isNotNull(bo.getSearchValue()), Course::getCourseFlag, bo.getSearchValue())
                .or()
                .like(ObjectUtil.isNotNull(bo.getSearchValue()), Course::getCourseDesc, bo.getSearchValue())
                .orderByDesc(Course::getUpdateTime);
    }

    /**
     * 新增课程
     */
    @Override
    public Boolean insertByBo(CourseBo bo) {
        verification(bo);
        Course add = BeanUtil.toBean(bo, Course.class);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setCourseId(add.getCourseId());
        }
        return flag;
    }

    /**
     * 修改课程
     */
    @Override
    public Boolean updateByBo(CourseBo bo) {
        verification(bo);
        Course update = BeanUtil.toBean(bo, Course.class);
        return baseMapper.updateById(update) > 0;
    }

    private void verification(CourseBo bo) {
        if (ObjectUtil.isNotNull(bo.getCourseBeginDate()) && ObjectUtil.isNotNull(bo.getCourseEndDate())) {
            if (bo.getCourseBeginDate().getTime() >= bo.getCourseEndDate().getTime()) {
                throw new ServiceException("开课时间不得晚于结课时间");
            } else {
                return;
            }
        } else if (ObjectUtil.isNull(bo.getCourseBeginDate()) && ObjectUtil.isNull(bo.getCourseEndDate())) {
            return;
        } else {
            throw new ServiceException("开课时间与结课时间必须同时存在");
        }
    }

    /**
     * 批量删除课程
     */
    @Transactional
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids) {
        // 删除对应的章节
        ids.forEach(id -> {
            Course course = baseMapper.selectById(id);
            if (course.getCourseEndDate().getTime() > new Date().getTime()) {
                throw new ServiceException(course.getCourseTitle() + ":未到达结课时间，课程不可删除");
            }
            Long count = planCourseMapper.selectCount(new QueryWrapper<PlanCourses>()
                    .eq("course_id", id));
            if (count.longValue() > 0) {
                throw new ServiceException("课程:" + course.getCourseTitle() + ",被学习计划引用，不可删除");
            }
            // 删除对应的章节
            chapterMapper.delete(new QueryWrapper<Chapter>().eq("course_id", id));
        });
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<Map<String, Object>> querySimpleList() {
        List<Course> courses = baseMapper.selectList();
        List<Map<String, Object>> lists = new ArrayList<>();
        courses.forEach(i -> {
            Map<String, Object> map = new HashMap<>();
            map.put("courseId", i.getCourseId());
            map.put("courseTitle", i.getCourseTitle());
            lists.add(map);
        });
        return lists;
    }
}
